package com.carepad.action;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;

public class AbstractCookieAction extends ActionSupport  implements ServletResponseAware, ServletRequestAware {

	private static final long serialVersionUID = 1L;
	
	protected static HttpServletResponse servletResponse;
	protected static HttpServletRequest servletRequest;

	@Override
	public void setServletResponse(HttpServletResponse servletResponse) {
		AbstractCookieAction.servletResponse = servletResponse;
	}

	@Override
	public void setServletRequest(HttpServletRequest servletRequest) {
		AbstractCookieAction.servletRequest = servletRequest;
	}
	
	public static void setCookie(String name, String value) {
		
	    try {
	    	
	    	String cval = getCookie(name);
	    	
		    if(cval == null) {
		    	
		    	Cookie cookie = new Cookie(name, value);  
				cookie.setMaxAge(60*60*24*7);
				cookie.setPath("/");
				servletResponse.addCookie(cookie); 
		    
		    } else if (!cval.equals(value)) {
		    	
		    	for (Cookie c : servletRequest.getCookies()) {
		            if (c.getName().equals(name)) {
		                c.setValue(value);
		                c.setMaxAge(60*60*24*7);
						c.setPath("/");
						servletResponse.addCookie(c);
		            }
		    	}
				
	    	} else {
	    		
	    		 return;
	    		
	    	}

	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	}

	public static String getCookie(String cookieName) {

		String value = null;

	    try {
	    	
	    	for (Cookie c : servletRequest.getCookies()) {
	            if (c.getName().equals(cookieName)) {
	                value = c.getValue();
	            }
	    	}

			return value;

	    } catch (Exception e) {
	    	e.printStackTrace();
	    }

	    return value;
	}
	
/*	public static void deleteCookie(String cookieName){
		
		for (Cookie c : servletRequest.getCookies()) {
	            if (c.getName().equals(cookieName)) {
	                c.setMaxAge(0);
		    		c.setValue(null);
		    		servletResponse.addCookie(c);
	            }
	}*/
}
